
package com.trial.area.trade.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.trial.area.common.controller.BaseController;
import com.trial.area.common.param.SessionUserInfo;
import com.trial.area.common.utils.ExcelUtil;
import com.trial.area.coupon.entity.CouponVO;
import com.trial.area.coupon.service.CouponService;
import com.trial.area.goods.entity.GoodsVO;
import com.trial.area.goods.service.GoodsService;
import com.trial.area.trade.entity.TradeRecordVO;
import com.trial.area.trade.param.TradeRecordParam;
import com.trial.area.trade.service.TradeRecordService;

/**
 * 交易信息Controller
 *
 * @author 朱国军
 * @since 1.0
 * @version 2015年12月27日 朱国军
 */
@Controller
public class TradeAdminController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(TradeAdminController.class);

    @Autowired
    private TradeRecordService tradeRecordService;

    @Autowired
    private GoodsService goodsService;
    
    @Autowired
    private CouponService couponService;

    private final static String ADMIN_LIST_PAGE = "/admin/trade/trade_list";

    private final static String ADMIN_AUDIT_LIST_PAGE = "/admin/trade/trade_audit_list";

    private final static String ADMIN_MANAGE_PAGE = "/admin/trade/trade_manage";
    
    @RequestMapping(value = "/admin/trade/list")
    public ModelAndView queryAdminList(TradeRecordParam tradeRecordParam) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<Map<String, Object>> dataList = tradeRecordService.queryByPage(tradeRecordParam);
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", tradeRecordParam);
        return new ModelAndView(ADMIN_LIST_PAGE, resultMap);
    }

    @RequestMapping(value = "/admin/trade/auditList")
    public ModelAndView queryAdminAuditList(TradeRecordParam tradeRecordParam) {
        Map<String, Object> resultMap = new HashMap<String, Object>();

        if (tradeRecordParam.getTradeState() == null || tradeRecordParam.getTradeState() == 0) {
            tradeRecordParam.setTradeState(2);
        }

        List<Map<String, Object>> dataList = tradeRecordService.queryByGoodsId(tradeRecordParam);
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", tradeRecordParam);
        return new ModelAndView(ADMIN_AUDIT_LIST_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/admin/trade/audit", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String audit(TradeRecordParam tradeRecordParam) {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            tradeRecordParam.setAuditUser(seUser.getUserId());
            resultMap = tradeRecordService.audit(tradeRecordParam);
        } catch (Exception e) {
            logger.error("删除交易信息出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "删除交易信息出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }
    
    /**
     * 根据条件导出券码
     *
     * @param couponParam
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/admin/trade/export")
    public ModelAndView export(TradeRecordParam tradeRecordParam) {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");
        
        String fileName = "订单列表";
        tradeRecordParam.setPageSize(Integer.MAX_VALUE);
        tradeRecordParam.setAuditUser(seUser.getUserId());

        List<Map<String, Object>> couponlist = tradeRecordService.queryByPage(tradeRecordParam);
        String columnNames[] = { "订单号", "订单状态", "商品名称", "商品属性", "购买备注", "收货人", "联系手机号", "收货地址-省份", "收货地址-城市", "收货地址-区县", "收货地址-详细地址", "物流公司",
            "物流单号" };// 列名
        String keys[] = { "trade_no", "trade_state_name", "goods_name", "select_property", "trade_remark", "contact_name", "contact_phone",
            "delivery_province", "delivery_city", "delivery_region", "delivery_address", "delivery_company", "delivery_no" };// map中的key
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ExcelUtil.createWorkBook("订单列表", couponlist, keys, columnNames).write(os);
        } catch (IOException e) {
            logger.error("订单导出Excel出错", e);
        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        
        ServletOutputStream out = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            // 设置response参数，可以打开下载页面
            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
            
            out = response.getOutputStream();
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            logger.error("订单导出Excel出错", e);
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    logger.error("订单导出Excel出错", e);
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    logger.error("订单导出Excel出错", e);
                }
            }
        }
        return null;
    }
    
    @RequestMapping(value = "/admin/trade/uploadExcel", produces = "text/html;charset=utf-8;")
    @ResponseBody
    public String uploadExcel(@RequestParam(value = "excelfile", required = false) MultipartFile excelfile) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            InputStream input = excelfile.getInputStream();
            Workbook workBook = WorkbookFactory.create(input);
            Sheet sheet = workBook.getSheetAt(0);
            List<Map<String, String>> tradeList = new ArrayList<Map<String, String>>();
            int minRowIx = sheet.getFirstRowNum();
            int maxRowIx = sheet.getLastRowNum();
            for (int rowIx = minRowIx + 1; rowIx <= maxRowIx; rowIx++) {
                Row row = sheet.getRow(rowIx);
                Map<String, String> tradeMap = new HashMap<String, String>();
                tradeMap.put("tradeNo", ExcelUtil.getCellValue(row.getCell(0)));
                tradeMap.put("deliveryCompany", ExcelUtil.getCellValue(row.getCell(11)));
                tradeMap.put("deliveryNo", ExcelUtil.getCellValue(row.getCell(12)));
                tradeList.add(tradeMap);
            }
            String resultString = tradeRecordService.updateDeliveryNo(tradeList);

            resultMap.put("result", true);
            resultMap.put("message", resultString.replaceFirst(",", ""));

        } catch (Exception e) {
            logger.error("导入Excel出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "更新物流信息出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }
    @RequestMapping(value = "/admin/trade/updateDeliveryNo", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String updateDeliveryNo(TradeRecordVO tradeRecordVO){
    	 Map<String, Object> resultMap = new HashMap<String, Object>();
         try {
             String resultString = tradeRecordService.updateDeliveryNo(tradeRecordVO);

             resultMap.put("result", true);
             resultMap.put("message", resultString.replaceFirst(",", ""));

         } catch (Exception e) {
             logger.error("更新物流信息出错", e);
             resultMap.put("result", false);
             resultMap.put("message", "更新物流信息出错：" + e.getLocalizedMessage());
         }
         return JSONObject.toJSONString(resultMap);
    }
    
    @RequestMapping(value = "/admin/trade/view/{id}")
    public ModelAndView adminView(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        TradeRecordVO tradeRecordVO = tradeRecordService.findById(id);
        resultMap.put("tradeRecordVO", tradeRecordVO);
        
        GoodsVO goodsVO = goodsService.findById(tradeRecordVO.getGoodsId());
        if (StringUtils.isNotBlank(goodsVO.getGoodsProperties())) {
            String[] properties = StringUtils.split(goodsVO.getGoodsProperties(), ":");
            String propertiesName = properties[0];
            resultMap.put("propertiesName", propertiesName);
        }
        
        resultMap.put("goodsVO", goodsVO);
        
        CouponVO couponVO = couponService.findById(tradeRecordVO.getCouponId());
        resultMap.put("couponVO", couponVO);
        
        return new ModelAndView(ADMIN_MANAGE_PAGE, resultMap);
    }
}
